package com.app.project.manager;

import com.app.project.common.ErrorCode;
import com.app.project.exception.BusinessException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import com.app.project.config.CosClientConfig;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * Cos 对象存储操作
 * @author
 * @from
 */
@Component
@Slf4j
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /**
     * 上传对象
     * @param key 唯一键
     * @param localFilePath 本地文件路径
     * @return
     */
    public PutObjectResult putObject(String key, String localFilePath) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, new File(localFilePath));
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传对象
     * @param key 唯一键
     * @param file 文件
     * @return
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 从输入流上传对象
     * @param key 唯一键
     * @param inputStream 输入流
     * @return
     */
    public PutObjectResult putObjectFromStream(String key, InputStream inputStream) {
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            // 如果无法预知内容长度，COS会使用chunked编码
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, inputStream, metadata);
            return cosClient.putObject(putObjectRequest);
        } catch (Exception e) {
            log.error("从流上传文件失败, key: {}", key, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        }
    }

    /**
     * 下载文件到本地
     * @param key 文件key
     * @param localFile 本地文件
     */
    public void getObject(String key, File localFile) {
        try {
            GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
            cosClient.getObject(getObjectRequest, localFile);
        } catch (Exception e) {
            log.error("下载文件失败, key: {}", key, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载失败");
        }
    }

    /**
     * 下载文件到输出流
     * @param key 文件key
     * @param outputStream 输出流
     */
    public void getObjectToStream(String key, OutputStream outputStream) {
        try {
            GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
            COSObject cosObject = cosClient.getObject(getObjectRequest);
            try (InputStream inputStream = cosObject.getObjectContent();
                 BufferedInputStream bis = new BufferedInputStream(inputStream, 64 * 1024)) {

                byte[] buffer = new byte[64 * 1024]; // 64KB缓冲区
                int bytesRead;
                while ((bytesRead = bis.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }
        } catch (Exception e) {
            log.error("下载文件到流失败, key: {}", key, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件下载失败");
        }
    }

    /**
     * 删除文件
     * @param key 文件key
     */
    public void deleteObject(String key) {
        try {
            cosClient.deleteObject(cosClientConfig.getBucket(), key);
        } catch (Exception e) {
            log.error("删除文件失败, key: {}", key, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件删除失败");
        }
    }

    /**
     * 批量删除文件
     * @param keys 文件key列表
     */
    public void deleteObjects(List<String> keys) {
        if (keys == null || keys.isEmpty()) {
            return;
        }

        try {
            // 腾讯云COS批量删除限制每次最多1000个对象
            int batchSize = 1000;
            for (int i = 0; i < keys.size(); i += batchSize) {
                List<String> batch = keys.subList(i, Math.min(i + batchSize, keys.size()));

                DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(cosClientConfig.getBucket());
                List<DeleteObjectsRequest.KeyVersion> keyVersions = new ArrayList<>();

                for (String key : batch) {
                    keyVersions.add(new DeleteObjectsRequest.KeyVersion(key));
                }

                deleteObjectsRequest.setKeys(keyVersions);
                // 静默模式，不返回删除成功的对象列表，减少响应体大小
                deleteObjectsRequest.setQuiet(true);

                DeleteObjectsResult result = cosClient.deleteObjects(deleteObjectsRequest);

                // 检查是否有删除失败的对象
                if (result.getDeletedObjects() != null && !result.getDeletedObjects().isEmpty()) {
                    log.info("批量删除成功: {} 个文件", result.getDeletedObjects().size());
                }


            }
        } catch (Exception e) {
            log.error("批量删除文件失败, keys: {}", keys, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "批量删除文件失败");
        }
    }

    /**
     * 检查文件是否存在
     * @param key 文件key
     * @return 是否存在
     */
    public boolean doesObjectExist(String key) {
        try {
            return cosClient.doesObjectExist(cosClientConfig.getBucket(), key);
        } catch (Exception e) {
            log.error("检查文件是否存在失败, key: {}", key, e);
            return false;
        }
    }
}
